//
//  UPPrivacyPolicyView.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/17.
//

#import "UPPrivacyPolicyView.h"
#import <Masonry/Masonry.h>

@interface UPPrivacyPolicyView ()
@property (nonatomic, strong) NSString *fullPolicyText;
@property (nonatomic, strong) NSString *highlightText;
@property (nonatomic, assign) NSRange highlightRange;
@end

@implementation UPPrivacyPolicyView

- (instancetype)initWithPolicyText:(NSString *)text highlightText:(NSString *)highlightText {
    self = [super init];
    if (self) {
        _fullPolicyText = text;
        _highlightText = highlightText;
        [self setupUI];
        [self setupConstraints];
        [self formatPolicyText];
    }
    return self;
}

- (void)setupUI {
    // 勾选按钮
    _checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_checkButton setImage:[UIImage imageNamed:@"privacy_policy_normal"] forState:UIControlStateNormal];
    [_checkButton setImage:[UIImage imageNamed:@"privacy_policy_selected"] forState:UIControlStateSelected];
    [_checkButton addTarget:self action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside];
    _checkButton.selected = YES;
    self.isSelected = _checkButton.selected;
    [self addSubview:_checkButton];
    
    // 政策文本
    _policyLabel = [[UILabel alloc] init];
    _policyLabel.numberOfLines = 0;
    _policyLabel.textAlignment = NSTextAlignmentCenter;
    _policyLabel.font = [UIFont systemFontOfSize:14];
    _policyLabel.userInteractionEnabled = YES;
    [self addSubview:_policyLabel];
}

- (void)setupConstraints {
    [_checkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self);
        make.top.equalTo(self).offset(4);
        make.width.height.mas_equalTo(12);
    }];
    
    [_policyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_checkButton.mas_right).offset(8);
        make.right.equalTo(self);
        make.top.equalTo(self.checkButton).offset(-2);
        make.bottom.equalTo(self);
    }];
}

- (void)formatPolicyText {
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:_fullPolicyText];
    
    // 设置基本样式
    NSDictionary *normalAttributes = @{
        NSFontAttributeName: [UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName: [UIColor blackColor]
    };
    [attributedText addAttributes:normalAttributes range:NSMakeRange(0, _fullPolicyText.length)];
    
    // 设置高亮文本样式
    _highlightRange = [_fullPolicyText rangeOfString:_highlightText];
    if (_highlightRange.location != NSNotFound) {
        NSDictionary *highlightAttributes = @{
            NSForegroundColorAttributeName: [UIColor redColor],
            NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle),
            NSUnderlineColorAttributeName: [UIColor redColor]
        };
        [attributedText addAttributes:highlightAttributes range:_highlightRange];
    }
    
    _policyLabel.attributedText = attributedText;
    
    // 添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [_policyLabel addGestureRecognizer:tap];
}

#pragma mark - Gesture Handling
- (void)handleTap:(UITapGestureRecognizer *)gesture {
    if (gesture.state != UIGestureRecognizerStateEnded) {
        return;
    }
    
    // 获取点击位置
    CGPoint location = [gesture locationInView:_policyLabel];
    
    // 创建文本容器
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:_policyLabel.bounds.size];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [layoutManager addTextContainer:textContainer];
    
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:_policyLabel.attributedText];
    [textStorage addLayoutManager:layoutManager];
    
    // 获取点击的字符索引
    CGFloat fraction;
    NSInteger characterIndex = [layoutManager characterIndexForPoint:location
                                                   inTextContainer:textContainer
                          fractionOfDistanceBetweenInsertionPoints:&fraction];
    
    // 检查是否点击了高亮文本
    if (NSLocationInRange(characterIndex, _highlightRange)) {
        if ([self.delegate respondsToSelector:@selector(privacyPolicyView:didTapHighlightText:)]) {
            [self.delegate privacyPolicyView:self didTapHighlightText:_highlightText];
        }
    } else {
        [self buttonTapped];
    }
}

#pragma mark - Button Action
- (void)buttonTapped {
    _checkButton.selected = !_checkButton.selected;
    self.isSelected = _checkButton.selected;
}

@end
